package com.quick.controller.system;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.quick.common.constants.CacheConstants;
import com.quick.common.core.controller.BaseController;
import com.quick.common.core.domain.ApiResponse;
import com.quick.common.redis.RedisCache;
import com.quick.common.utils.SecurityUtils;
import com.quick.system.domain.SysMenu;
import com.quick.system.domain.SysUser;
import com.quick.system.domain.dto.LoginDTO;
import com.quick.system.service.*;
import io.lettuce.core.ScriptOutputType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 *
 * @Author: 吃素不吃肉
 * @Date: Tue Jul 25 14:14:44 CST 2023
 */
@RestController
public class SysLoginController extends BaseController {
    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public ApiResponse getCode() {
        // 保存验证码信息
        String uuid = UUID.randomUUID().toString();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String capStr;
        String code;
        BufferedImage image;
        capStr = code = defaultKaptcha.createText();
        image = defaultKaptcha.createImage(capStr);
        redisCache.setCacheObject(verifyKey, code, 3, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return error();
        }
        Map<String, Object> verificationCode = new HashMap<>(2);
        verificationCode.put("uuid", uuid);
        verificationCode.put("img", Base64.getEncoder().encodeToString(os.toByteArray()));
        return success(verificationCode);
    }

    /**
     * 登录方法
     *
     * @param loginDTO 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public ApiResponse login(@RequestBody LoginDTO loginDTO) {
        return success(sysLoginService.login(loginDTO));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping(value = "/getInfo")
    public ApiResponse getInfo() {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        SysUser sysUser = sysUserService.selectSysUserByUserId(userId);
        // 角色集合
        Set<String> roles = sysRoleService.selectRoleKeyByUserId(userId);
        // 权限集合
        Set<String> permissions = sysMenuService.selectSysMenuPermsByUserId(userId);
        Map<String, Object> userInfo = new HashMap<>(3);
        userInfo.put("user", sysUser);
        userInfo.put("roles", roles);
        userInfo.put("permissions", permissions);
        return success(userInfo);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping(value = "/getRouters")
    public ApiResponse getRouters() {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        List<SysMenu> menus = sysMenuService.selectMenuTreeByUserId(userId);
        return success(sysMenuService.buildMenus(menus));
    }
}
